<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\models\business\BusinessCost;
use common\models\business\BusinessCostType;
use common\models\business\BusinessFarmers;
use common\models\business\BusinessPig;
use EasyWeChat\Support\Arr;
use Yii;
use common\models\business\BusinessBackpig;
use backend\modules\business\models\BusinessBackpigSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * BackpigController implements the CRUD actions for BusinessBackpig model.
 */
class BackpigController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessBackpig models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessBackpigSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessBackpig model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $cost = (new Query())->select(['status','type','FROM_UNIXTIME(createtime,"%Y-%m-%d") as createtime','person','price'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
        if(!empty($cost)){
            foreach ($cost as $key => $row){
                $cost[$key]['status'] = BusinessCost::$statues[$row['status']];
            }
        }
        return $this->render('view', [
            'model' => $model,
            'cost' => $cost
        ]);
    }

    /**
     * Creates a new BusinessBackpig model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessBackpig();
        $cost = (new Query())->select(['status','type','FROM_UNIXTIME(createtime,"%Y-%m-%d") as createtime','person','price'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
        if ($model->load(Yii::$app->request->post())) {
            $pmodel = BusinessPig::findOne($model->pigid);
            if(empty($pmodel)){
                return $this->dialog('填写的仔猪不存在');
            }
            $model->cost = serialize($cost);
            $model->pigno = $pmodel->no;
            if($model->save()){

                $post = Yii::$app->request->post();


                $offset = 0;
                if(!empty($post['costid'])){
                    //取出要删除的成本
                    $costids = (new Query())->select(['id'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
                    $ids = ArrayHelper::getColumn($costids,'id');
                    $delids = array_diff($ids,$post['costid']);
                    if(!empty($delids)){
                        $res = Yii::$app->db->createCommand()->delete(BusinessCost::tableName(),'id in (:id)',[':id'=>implode(',',$delids)])->execute();
                    }

                    //更新成本的状态
                    foreach ($post['costid'] as $key => $row){
                        $data['status'] = BusinessCost::$statues[$post['status'][$key]];
                        Yii::$app->db->createCommand()->update(BusinessCost::tableName(),['status'=>$post['status'][$key]],'id=:id',[':id'=>$row]);
                    }

                    $offset = count($post['costid']);
                }





                //取出类型
                $costtype = BusinessCostType::find()->select('name,id')->where(['type'=>BusinessCostType::TYPE_PIG])->indexBy('id')->asArray()->all();
                if(!empty($post['costtype'])){
                    foreach ($post['costtype'] as $key => $value){
                        $data = [
                            'typeid' => $value,
                            'type' => $costtype[$value]['name'],
                            'pigid' => $model->pigid,
                            'personid' => 0,
                            'person' => Yii::$app->user->identity->username,
                            'price' => $post['price'][$key],
                            'createtime' => strtotime($post['createtime'][$key]),
                            'description' => $post['description'][$key],
                        ];
                        if($key >= $offset){
                            $data['status'] = $post['status'][$key];
                        }
                        $res = Yii::$app->db->createCommand()->insert(BusinessCost::tableName(),$data)->execute();
                    }
                }

                //取出成本更新到回购单中的
                $cost = (new Query())->select(['status','type','id','description','FROM_UNIXTIME(createtime,"%Y-%m-%d") as createtime','person','price'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
                if(!empty($cost)){
                    foreach ($cost as $key => $row){
                        $cost[$key]['status'] = BusinessCost::$statues[$row['status']];
                    }
                }
                $model->cost = serialize($cost);
                $model->save();
                return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->dialog($this->checkError($model));
        } else {

            $costtype = BusinessCostType::find()->select("*")->where('type=:type',[':type'=>BusinessCostType::TYPE_PIG])->asArray()->all();
            return $this->render('create', [
                'model' => $model,
                'costtype' => $costtype
            ]);
        }
    }

    /**
     * Updates an existing BusinessBackpig model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $pmodel = BusinessPig::findOne($model->pigid);


        if ($model->load(Yii::$app->request->post())) {
            $post = Yii::$app->request->post();

            $costids = (new Query())->select(['id'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
            //取出要删除的成本
            $post['costid'] = array_key_exists('costid',$post)?$post['costid']:[];
            $ids = ArrayHelper::getColumn($costids, 'id');
            $delids = array_diff($ids, $post['costid']);
            if (!empty($delids)) {
//                $res = Yii::$app->db->createCommand()->delete(BusinessCost::tableName(), 'id in (:id)', [':id' => implode(',', $delids)])->execute();
                $res = Yii::$app->db->createCommand()->delete(BusinessCost::tableName(),['id'=>$delids])->execute();
            }

            //更新成本的状态
            foreach ($post['costid'] as $key => $row){
                $data['status'] = BusinessCost::$statues[$post['status'][$key]];
                Yii::$app->db->createCommand()->update(BusinessCost::tableName(),['status'=>$post['status'][$key]],'id=:id',[':id'=>$row])->execute();
            }

            //取出类型
            $costtype = BusinessCostType::find()->select('name,id')->where(['type'=>BusinessCostType::TYPE_PIG])->indexBy('id')->asArray()->all();
            if(!empty($post['costtype'])){
                foreach ($post['costtype'] as $key => $value){
                    $data = [
                        'typeid' => $value,
                        'type' => $costtype[$value]['name'],
                        'pigid' => $model->pigid,
                        'personid' => 0,
                        'person' => Yii::$app->user->identity->username,
                        'price' => $post['price'][$key],
                        'createtime' => strtotime($post['createtime'][$key]),
                        'description' => $post['description'][$key],
                    ];
                    if(!empty($post['costid'])){
                        $data['status'] = $post['status'][count($post['costid'])-$key];
                    }else{
                        $data['status'] = $post['status'][$key];
                    }
                    $res = Yii::$app->db->createCommand()->insert(BusinessCost::tableName(),$data)->execute();
                }
            }

            //取出成本更新到回购单中的
            $cost = (new Query())->select(['status','type','id','description','FROM_UNIXTIME(createtime,"%Y-%m-%d") as createtime','person','price'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
            if(!empty($cost)){
                foreach ($cost as $key => $row){
                    $cost[$key]['status'] = BusinessCost::$statues[$row['status']];
                }
            }
            if(empty($pmodel)){
                return $this->dialog('填写的仔猪不存在');
            }
            $model->cost = serialize($cost);
            $model->pigno = $pmodel->no;
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
            return $this->dialog($this->checkError($model));
        }else {

            $costtotal = 0.00;
            $cost = (new Query())->select(['status','type','id','description','FROM_UNIXTIME(createtime,"%Y-%m-%d") as createtime','person','price'])->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>$model->pigid])->all();
            if(!empty($cost)){
                foreach ($cost as $key => $row){

                    if($cost[$key]['status'] == BusinessCost::STATUS_CONFIRM){
                        $costtotal += $row['price'];
                    }
                    $cost[$key]['status'] = BusinessCost::$statues[$row['status']];
                }
            }
            $costtype = BusinessCostType::find()->select("*")->where('type=:type',[':type'=>BusinessCostType::TYPE_PIG])->asArray()->all();

            $model->backtotal = ($model->backprice*$model->grossweight)+$costtotal;
            return $this->render('update', [
                'model' => $model,
                'cost' => $cost,
                'costtype' => $costtype
            ]);
        }
    }

    /**
     * Deletes an existing BusinessBackpig model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessBackpig model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessBackpig the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessBackpig::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSearchcost()
    {
        $pmodel = BusinessPig::findOne(Yii::$app->request->post('pigid'));
        $cost = [];
        $cost['data'] = (new Query())->select('id,status,type,createtime,person,price,description')->from(BusinessCost::tableName())->where('pigid=:pigid',[':pigid'=>Yii::$app->request->post('pigid')])->all();
        if(!empty($cost['data'])){
            foreach ($cost['data'] as $key => $row){
                $cost['data'][$key]['status'] = BusinessCost::$statues[$row['status']];
                $cost['data'][$key]['createtime'] = date('Y-m-d',$row['createtime']);
            }
        }
        $cost['farmerid'] = $pmodel->livery;
        $cost['farmername'] = $pmodel->liveryname;
        return \GuzzleHttp\json_encode($cost);
    }


    /**
     * 待审核的单
     */
    public function actionAgree()
    {
        $searchModel = new BusinessBackpigSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('agree', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);

    }


    public function actionOpagree()
    {
        $op = Yii::$app->request->get('op');
        $agreeuser = Yii::$app->user->identity->username;
        if($op == 'agree'){
            //确认回购的话直接进行出栏操作
            Yii::$app->db->createCommand()->update(BusinessPig::tableName(),['status'=>BusinessPig::STATUS_WAITOUT],'id=:id',[':id'=>Yii::$app->request->get('pigid')])->execute();
            $res = Yii::$app->db->createCommand()->update(BusinessBackpig::tableName(),['status'=>BusinessBackpig::STATUS_AGREE,'agreeuser'=>$agreeuser],'id=:id',[':id'=>Yii::$app->request->get('id')])->execute();
        }else{
            $res = Yii::$app->db->createCommand()->update(BusinessBackpig::tableName(),['status'=>BusinessBackpig::STATUS_DISAGREE,'agreeuser'=>$agreeuser],'id=:id',[':id'=>Yii::$app->request->get('id')])->execute();
        }
        return $res?$this->dialog('操作成功'):$this->dialog('操作失败');

    }




}
